package syslog

import (
	"context"
	"fmt"
	"gitee.com/bobo-rs/creative-framework/pkg/utils"
	"gitee.com/bobo-rs/creative-services/enums"
	"gitee.com/bobo-rs/creative-services/framework/dao"
	"gitee.com/bobo-rs/creative-services/framework/model"
	"gitee.com/bobo-rs/creative-services/framework/model/entity"
	"gitee.com/bobo-rs/creative-services/framework/service"
	"gitee.com/bobo-rs/creative-services/library/exception"
	"github.com/gogf/gf/v2/encoding/gjson"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"strings"
)

// SaveSystemLog 保存系统日志
func (l *sSysLog) SaveSystemLog(ctx context.Context, log entity.SystemLog) error {
	// 用户信息
	if userAuth := service.BizCtx().GetUser(ctx); userAuth != nil {
		log.UserId = userAuth.Uid
	}

	// 管理员信息
	if admAuth := service.User().GetAdminUser(ctx); admAuth != nil {
		log.ManageId = admAuth.Id
		log.ManageName = admAuth.ManageName
	}

	// 实例客户端
	fromCtx := ghttp.RequestFromCtx(ctx)

	// 记录Ip
	log.Ip = fromCtx.GetClientIp()

	// 响应参数
	if body := fromCtx.GetFormMap(); len(body) > 0 {
		log.ParamText = gjson.MustEncodeString(body)
	}

	// 根据URL地址截取Module名
	if len(log.ApiUrl) > 0 {
		log.ModuleName = strings.Split(utils.Slugify(log.ApiUrl), `-`)[0]
	}

	// 保存数据
	_, err := dao.SystemLog.Ctx(ctx).Insert(log)
	if err != nil {
		return exception.New(`添加日志失败`)
	}
	return nil
}

// RecordLog 记录系统日志数据
func (l *sSysLog) RecordLog(ctx context.Context, op enums.LogOperateType, item model.RecordLogItem) error {
	// 保存日志
	return l.SaveSystemLog(ctx, entity.SystemLog{
		OperateType:  int(op),
		Content:      item.Content,
		ApiUrl:       item.ApiUrl,
		ResponseText: item.ResponseText,
	})
}

// GetSystemLogList 获取系统日志列表
func (l *sSysLog) GetSystemLogList(ctx context.Context, in model.SystemLogGetListInput) (out *model.SystemLogGetListOutput, err error) {
	out = &model.SystemLogGetListOutput{}
	// 获取日志列表
	err = l.LogModel().ListAndTotal(ctx, model.CommonListAndTotalInput{
		Where:                l.SystemLogWhere(in.SystemLogWhereItem),
		CommonPaginationItem: in.CommonPaginationItem,
		Sort:                 fmt.Sprintf(`%s desc`, dao.SystemLog.Columns().Id),
	}, &out.Rows, &out.Total)
	if err != nil {
		return nil, exception.New(`暂无数据`)
	}

	// 到底了
	if len(out.Rows) == 0 {
		return
	}

	// 格式化数据
	for _, item := range out.Rows {
		detail := model.SystemLogDetailItem{
			SystemLogItem:    item.SystemLogItem,
			SystemLogFmtItem: item.SystemLogFmtItem,
		}
		// 格式化
		l.FormatSystemLog(&detail)
		item.SystemLogFmtItem = detail.SystemLogFmtItem
	}
	return
}

// GetSystemLogDetail 获取系统日志详情
func (l *sSysLog) GetSystemLogDetail(ctx context.Context, id uint) (out *model.SystemLogGetDetailOutput, err error) {
	out = &model.SystemLogGetDetailOutput{}
	// 获取数据
	err = l.LogModel().Scan(ctx, g.Map{
		dao.SystemLog.Columns().Id: id,
	}, &out.SystemLogDetailItem)

	if err != nil {
		return nil, exception.New(`暂无日志`)
	}

	// 格式化
	l.FormatSystemLog(out.SystemLogDetailItem)
	return
}
